package com.caocaog.market.service.impl;

import com.alibaba.fastjson.JSON;
import com.caocaog.market.entity.GoodsAttr;
import com.caocaog.market.entity.GoodsBase;
import com.caocaog.market.entity.GoodsHis;
import com.caocaog.market.entity.GoodsSpec;
import com.caocaog.market.mapper.GoodsHisMapper;
import com.caocaog.market.service.GoodsAttrService;
import com.caocaog.market.service.GoodsHisService;
import com.caocaog.market.service.GoodsSpecService;
import lombok.RequiredArgsConstructor;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.base.entity.FieldRedisItem;
import org.jeecg.common.system.base.service.impl.GenericServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * mk_goods_his
 *
 * @author jeecg-boot
 * @date 2021-11-20
 */
@Service
@RequiredArgsConstructor
public class GoodsHisServiceImpl extends GenericServiceImpl<GoodsHisMapper, GoodsHis> implements GoodsHisService {

    private GoodsSpecService goodsSpecService;
    private GoodsAttrService goodsAttrService;

    /**
     * 插入商品历史信息
     *
     * @param goodsBase 商品基础信息
     * @return 商品历史信息
     */
    @Override
    public int insertGoodsHis(GoodsBase goodsBase) {
        GoodsHis goodsHis = new GoodsHis(goodsBase)
                .setGoodsAttr(JSON.toJSONString(this.goodsAttrService.getGoodsAttrByGoodsId(goodsBase.getId())))
                .setGoodsSpec(JSON.toJSONString(this.goodsSpecService.getGoodsSpecByGoodsId(goodsBase.getId())));
        return super.insertCache(goodsHis);
    }

    /**
     * 插入商品历史信息
     *
     * @param goodsBase     商品基础信息
     * @param goodsAttrList 商品属性集合
     * @param goodsSpecList 商品规格信息
     * @return 商品历史信息
     */
    @Override
    public GoodsHis insertGoodsHis(GoodsBase goodsBase, List<GoodsAttr> goodsAttrList, List<GoodsSpec> goodsSpecList) {
        GoodsHis goodsHis = new GoodsHis(goodsBase)
                .setGoodsAttr(JSON.toJSONString(goodsAttrList))
                .setGoodsSpec(JSON.toJSONString(goodsSpecList));
        super.insertCache(goodsHis);
        return super.getByIdCache(goodsHis.getId());
    }


    @Autowired
    public void setGoodsAttrService(GoodsAttrService goodsAttrService) {
        this.goodsAttrService = goodsAttrService;
    }
    @Autowired
    public void setGoodsSpecService(GoodsSpecService goodsSpecService) {
        this.goodsSpecService = goodsSpecService;
    }

    @Override
    public String getName() {
        return "商品历史";
    }

    @Override
    public List<FieldRedisItem<GoodsHis>> getAllFieldCacheList() {
        return Collections.singletonList(FieldRedisItem.build(GoodsHis::getId, CacheConstant.GOODS_HIS_INFO, true));
    }
}
